package com.app.ui.activity.video;

import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.app.ui.activity.action.BaseBarActivity;
import com.app.utiles.other.APKInfo;
import com.app.utiles.other.DLog;
import com.app.utiles.other.FileUtile;
import com.wxj.zx.R;

import java.io.IOException;


/**
 * 视频录制
 * Created by 郭敏 on 2018/1/31 0031.
 */

public class BaseVideoActionActivity extends BaseBarActivity implements View.OnClickListener {
    private Button videoBtn;
    protected TextureView textureview;
    //视频录制状态
    protected boolean isRecording;
    //true 前置相机
    protected boolean isCameraFront = false;
    private MediaRecorder mediaRecorder;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        // 设置竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 选择支持半透明模式,在有surfaceview的activity中使用。
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        //
        setContentView(R.layout.activity_video);
        videoBtn = (Button) findViewById(R.id.video_btn);
        videoBtn.setOnClickListener(this);
        findViewById(R.id.video_rest_tv).setOnClickListener(this);
        findViewById(R.id.picture_tv).setOnClickListener(this);
        findViewById(R.id.camera_switchover_tv).setOnClickListener(this);
        findViewById(R.id.camera_light_tv).setOnClickListener(this);

        //画布
        textureview = (TextureView) findViewById(R.id.textureview);
        textureview.setSurfaceTextureListener(new SurfaceCallback());
        textureview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                //两指缩放
                recordingVideoZoom(event);
                return true;
            }
        });
        //
    }


    //获取录音
    protected MediaRecorder getMediaRecorder() {
        return mediaRecorder;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.camera_light_tv:
                //相机灯光
                cameraLight();
                break;
            case R.id.camera_switchover_tv:
                //切换摄像头
                cameraSwitchover();
                break;
            case R.id.video_rest_tv:
                //重新开始预览
                restCameraPreview();
                break;
            case R.id.picture_tv:
                //拍照
                picture();
                break;
            case R.id.video_btn:
                //录制视频
                isRecording = !isRecording;
                recordingVideo(isRecording);
                break;
        }

    }

    //相机灯光
    protected void cameraLight() {

    }

    //切换摄像头
    protected void cameraSwitchover() {

    }

    //拍照
    protected void picture() {

    }

    //重新显示相机预览
    protected void restCameraPreview() {

    }

    protected String getVoidPath() {
        String videoPath = FileUtile.getVoideoCacheFilePath("测试2.mp4");
        return videoPath;
    }

    protected String getImagePath() {
        String imagePath = FileUtile.getImageFilePath("test.png");
        return imagePath;
    }

    //录制视频 isRecording:true(开始录制) fals(停止录制)
    protected void recordingVideo(boolean isRecording) {
        try {
            if (isRecording) {
                mediaRecorder.start();
                videoBtn.setText("停止");
                return;
            }
            //停止录制
            mediaRecorder.stop();
            //重置
            mediaRecorder.reset();
            videoBtn.setText("开始");
            videoPlay();
        } catch (Exception e) {
            e.printStackTrace();
            videoBtn.setText("发生错误");
            DLog.e("录制视频,发生错误", "isRecording:" + isRecording + "--" + e.getMessage());
        }
    }

    //录制视频时 可以缩放
    protected void recordingVideoZoom(MotionEvent event) {
    }


    //设置录制视频的配置(到已准备)
    protected void setVideoConfiguration() {
        if (isRecorderRelease || mediaRecorder == null) {
            mediaRecorder = new MediaRecorder();
            isRecorderRelease = false;
        }
        mediaRecorder.setPreviewDisplay(new Surface(textureview.getSurfaceTexture()));

        // 设置音频采集方式
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        //设置视频的采集方式
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        //获取相机的配置
        // CamcorderProfile profile=CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
        // mediaRecorder.setProfile(profile);
        int h = (int) APKInfo.getInstance().getScreenHeightPixels();
        int w = (int) APKInfo.getInstance().getScreenWidthPixels();
        //设置文件的输出格式
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//aac_adif， aac_adts， output_format_rtp_avp， output_format_mpeg2ts ，webm
        //设置audio的编码格式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //设置video的编码格式
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //设置录制的视频编码比特率(可以调整清晰度)
        mediaRecorder.setVideoEncodingBitRate(5 * 1920 * 1080);
        //设置录制的视频帧率(要硬件支持)
        mediaRecorder.setVideoFrameRate(30);
        //设置记录会话的最大持续时间（毫秒）
        //mediaRecorder.setMaxDuration(60 * 1000);
        mediaRecorder.setVideoSize(h, w);
        //竖屏后置摄像头
        if (!isCameraFront) {
            mediaRecorder.setOrientationHint(90);
        } else {
            mediaRecorder.setOrientationHint(270);
        }
        try {
            //设置输出文件的路径
            mediaRecorder.setOutputFile(getVoidPath());
            //准备录制
            mediaRecorder.prepare();
        } catch (IOException e) {
            DLog.e("视频录制", "准备失败");
            e.printStackTrace();
        }
    }

    //视频播放
    protected void videoPlay() {
        if (isPlayeRelease || mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(new CompletionListener());
            mediaPlayer.setOnPreparedListener(new PreparedListener());
            mediaPlayer.setOnErrorListener(new ErrorListener());
            isPlayeRelease = false;
        }
        try {
            mediaPlayer.reset();
            SurfaceTexture surfaceTexture = textureview.getSurfaceTexture();
            mediaPlayer.setSurface(new Surface(surfaceTexture));
            mediaPlayer.setDataSource(getVoidPath());
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            DLog.e("视频播放发送错误", e.getMessage());
        }

    }

    //停止播放
    protected void videoStop() {
        if (!mediaPlayer.isPlaying()) {
            return;
        }
        mediaPlayer.pause();
        mediaPlayer.stop();
        mediaPlayer.reset();
    }

    //开启相机
    protected void openCamera() {
    }

    //------------=---------------览视图相关开始-----------------------
    class SurfaceCallback implements TextureView.SurfaceTextureListener {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //当SurefaceTexture可用的时候，设置相机参数并打开相机
            openCamera();
            DLog.e("预览可用", "onSurfaceTextureAvailable width：" + width + " height:" + height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            DLog.e("预览大小发生改变", "onSurfaceTextureSizeChanged");
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            DLog.e("预览停止", "onSurfaceTextureDestroyed");
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
            //   DLog.e("预览发生更新", "onSurfaceTextureUpdated");
        }

    }

    //------------=---------------览视图相关结束-----------------------
    //------------------------视频播放相关----------------------------------
    //播放完成视频
    class CompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            mediaPlayer.start();
            DLog.e("视频播放完成", "---------------------");
        }
    }

    //准备完成
    class PreparedListener implements MediaPlayer.OnPreparedListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            mediaPlayer.start();
            DLog.e("视频准备完成", "---------------------");
        }
    }

    class ErrorListener implements MediaPlayer.OnErrorListener {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            mediaPlayer.reset();
            DLog.e("视频发生错误", "---------------------");
            return true;
        }
    }

    //------------------------视频播放相关结束----------------------------------
    private boolean isRecorderRelease;
    private boolean isPlayeRelease;

    //释放资源
    protected void release() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
        }
        if (mediaRecorder != null) {
            mediaRecorder.release();
        }
        isRecorderRelease = true;
        isPlayeRelease = true;
    }

}
